//
//  EFALoginVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFALoginVC.h"
#import "EFABindPhoneVC.h"
#import "TTTAttributedLabel.h"
#import "EFAWebViewVC.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFARootVC.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "EFAModel.h"
#import "EFALoginNavC.h"
#import "GTSDK/GeTuiSdk.h"

@interface EFALoginVC ()<TTTAttributedLabelDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *verifyCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *getVerifyBtn;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet TTTAttributedLabel *protocolTTTLabel;
@property (weak, nonatomic) IBOutlet UIView *wechatBgView;
@property (weak, nonatomic) IBOutlet UIButton *wechatBtn;
@end

@implementation EFALoginVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLogicData];
    [self initNavigationBar];
    [self initSubViews];
}
- (void)initLogicData {
    if (!self.viewType) {
        self.viewType = ((EFALoginNavC *)self.navigationController).viewType;
    }
}
- (void)initNavigationBar {
    self.navigationItem.title = (self.viewType == 1) ? @"短信登录" : @"密码登录";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
- (void)initSubViews {
    [self.phoneTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.verifyCodeTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    NSString *placeHolder = (self.viewType == 1) ? @"请输入验证码" : @"请输入密码(默认6666)";
    self.verifyCodeTextField.placeholder = placeHolder;
    self.verifyCodeTextField.secureTextEntry = (self.viewType == 2);
    self.verifyCodeTextField.keyboardType = (self.viewType == 1 ? UIKeyboardTypeNumberPad : UIKeyboardTypeDefault);
    
    self.getVerifyBtn.layer.masksToBounds = YES;
    self.getVerifyBtn.layer.cornerRadius = 4;
    [self.getVerifyBtn addTarget:self action:@selector(getVerifyBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    NSString *btnTitle = (self.viewType == 1) ? @"获取验证码" : @"短信登录";
    [self.getVerifyBtn setTitle:btnTitle forState:UIControlStateNormal];
    self.startBtn.layer.masksToBounds = YES;
    self.startBtn.layer.cornerRadius = 4;
    [self.startBtn addTarget:self action:@selector(startBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.wechatBtn addTarget:self action:@selector(wechatBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.protocolTTTLabel.linkAttributes = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen]};
    self.protocolTTTLabel.activeLinkAttributes = nil;
    self.protocolTTTLabel.inactiveLinkAttributes = nil;
    NSString *linkStr = [NSString stringWithFormat:@"《%@》", EFAGlobalFileAppTermServer];
    NSString *protocolStr = [NSString stringWithFormat:@"点击开始，即表示已阅读并同意%@", linkStr];
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:EFAGlobalFileAppTermServer ofType:@"docx"]];
    NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:protocolStr];
    [mAStr addAttributes:@{NSLinkAttributeName : url} range:[protocolStr rangeOfString:linkStr]];
    [mAStr addAttributes:@{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:EFAGlobalColorFontMidBlack]} range:[protocolStr rangeOfString:protocolStr]];
    self.protocolTTTLabel.text = mAStr;
    self.protocolTTTLabel.delegate = self;
    
    // 暂时屏蔽掉微信登录
    self.wechatBgView.hidden = YES;
    
    self.phoneTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:EFAGlobalUserDefaultsAccount];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - TTTAttributedLabelDelegate
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
    if ([url isKindOfClass:[NSURL class]]) {
        [self jumpToWebViewWithUrl:url];
    }
}

#pragma mark - event response
- (void)textFieldDidChange:(UITextField *)textField {
    if (self.phoneTextField.text.length && self.verifyCodeTextField.text.length) {
        [self setButton:self.startBtn enabled:YES];
    } else {
        [self setButton:self.startBtn enabled:NO];
    }
}
- (void)getVerifyBtnTapped:(UIButton *)btn {
    if (self.viewType == 2) {
        [self jumpToSMSLoginVC];
        return;
    }
    
    // 校验手机号
    if (![self checkPhoneNum]) {
        return;
    }
    // 倒计时
    [self startTime];
    // 请求网络
    [self requestVerifyCode];
}
- (void)startBtnTapped:(UIButton *)btn {
    if (![self checkPhoneNum]) {
        return;
    }
    
    if (self.viewType == 1 && ![self checkVerifyCode]) {
        return;
    }
    
    if (self.viewType == 2 && ![self checkPassword]) {
        return;
    }
    
    [self requestLogin];
}
- (void)wechatBtnTapped:(UIButton *)btn {
//    EFABindPhoneVC *vc = [[EFABindPhoneVC alloc] init];
    UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"EFABindPhoneVC"];
    [self showViewController:vc sender:nil];
}

#pragma mark - private methods
- (void)setButton:(UIButton *)btn enabled:(BOOL)enabled {
    [btn setEnabled:enabled];
    UIColor *color = enabled ? [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen] : [UIColor xd_colorWithHex:EFAGlobalColorLightGreen];
    [btn setBackgroundColor:color];
}
- (void)jumpToWebViewWithUrl:(NSURL *)url {
    EFAWebViewVC *vc = [[EFAWebViewVC alloc] init];
    vc.titleStr = EFAGlobalFileAppTermServer;
    vc.requestUrl = url;
    [self showViewController:vc sender:nil];
}
- (void)jumpToSMSLoginVC {
    EFALoginVC *loginVC = [self.storyboard instantiateViewControllerWithIdentifier:@"EFALoginVC"];
    loginVC.viewType = 1;
    [self showViewController:loginVC sender:nil];
}
- (void)jumpToRootVC {
//    EFARootVC *vc = [[EFARootVC alloc] initWithRefreshUserInfo:NO];
//    [UIApplication sharedApplication].keyWindow.rootViewController = vc;
//
//    //转场动画
//    CATransition *anim = [CATransition animation];
////    anim.type = @"rippleEffect";
//    anim.type = @"reveal";
//    anim.duration = 0.5;
//    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:EFAGlobalNotiLoginRootVC object:nil userInfo:nil];
}
- (BOOL)checkPhoneNum {
    if (self.phoneTextField.text.length != EFAGlobalPhoneNumLength) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入11位数的手机号"];
        return NO;
    }
    
    return YES;
}
- (BOOL)checkVerifyCode {
    if (self.verifyCodeTextField.text.length != EFAGlobalVerifyCodeLength) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入4位验证码"];
        return NO;
    }
    
    return YES;
}
- (BOOL)checkPassword {
    if (!self.verifyCodeTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入密码"];
        return NO;
    }
    
    return YES;
}
- (void)startTime{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
//                [self.getVerifyBtn setBackgroundColor:[UIColor xd_colorWithHex:EFAGlobalColorDarkGreen]];
//                self.getVerifyBtn.userInteractionEnabled = YES;
                [self.getVerifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self setButton:self.getVerifyBtn enabled:YES];
            });
        }else{
            int seconds = timeout % 60 ;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                //                [UIView beginAnimations:nil context:nil];
                //                [UIView setAnimationDuration:1];
//                [self.getVerifyBtn setBackgroundColor:[UIColor xd_colorWithHex:EFAGlobalColorLightGreen]];
//                self.getVerifyBtn.userInteractionEnabled = NO;
                [self.getVerifyBtn setTitle:[NSString stringWithFormat:@"已发送(%@)", strTime] forState:UIControlStateNormal];
                //                [UIView commitAnimations];
                [self setButton:self.getVerifyBtn enabled:NO];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
#pragma mark - network request
- (void)requestVerifyCode {
    NSDictionary *parameters = @{@"phonenumber" : self.phoneTextField.text};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCheckCode] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求验证码返回成功:%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求验证码失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestLogin {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{///< 短信登录
                           @"efairy_phonenumber" : self.phoneTextField.text,
                           @"check_code" : self.verifyCodeTextField.text,
                           ///< 密码登录
                           @"efairyuser_phonenumber" : self.phoneTextField.text,
                           @"efairyuser_password" : self.verifyCodeTextField.text,
                           @"gt_cid" : [GeTuiSdk clientId]//个推clientId
                           };
    
    NSString *url = (self.viewType == 1) ? [ApiManager apiLogin] : [ApiManager apiPwdLogin];
    [[XDAFNetworking sharedInstance] GET:url parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        //绑定相关信息
        [[EFAModel sharedInstance] loginModelWithDictionary:responseObject];
        [self jumpToRootVC];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
#pragma mark - getters and setters
@end
